import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    // 添加待办事项的下一个id
    nextId: 5,
    // 文本框
    inputValue: '',
    // 默认显示全部面板
    viewkey: 'all'
  },
  mutations: {
    // 获取待办事项数组
    getList(state, list) {
      state.list = list
    },
    // 删除某一项待办事项
    deleteList(state, id) {
      const i = state.list.findIndex(x => x.id === id)
      if (i !== -1) {
        console.log('删除的id：', id)
        state.list.splice(i, 1)
      }
    },
    // 修改store中的inputValue值
    editInputValue(state, data) {
      state.inputValue = data
    },
    // 添加事项
    addList(state) {
      const param = {
        id: state.nextId,
        info: state.inputValue,
        done: false
      }
      state.list.push(param)
      state.nextId++
      state.inputValue = ''
    },
    // 清空已完成
    clearDone(state) {
      state.list = state.list.filter(x => x.done === false)
    },
    // 待办事项复选框选中状态取反
    changeDone(state, id) {
      const i = state.list.findIndex(x => x.id === id)
      if (i !== -1) {
        state.list[i].done = !state.list[i].done
      }
    },
    // 修改面板对应的viewkey值
    chageViewKey(state, value) {
      state.viewkey = value
      console.log('viewkey:', state.viewkey)
    }
  },
  actions: {
    // 获取待办事项数组
    AgetList(context) {
      axios.get('/todoList.json').then(res => {
        if (res.status === 200) {
          // console.log(res)
          context.commit('getList', res.data)
        }
      })
    }
  },
  modules: {},
  getters: {
    // 未完成的待办事项条数
    unDoneNum(state) {
      return state.list.filter(x => x.done === false).length
    },
    // 根据面板去相应数据
    infoList(state) {
      if (state.viewkey === 'all') {
        return state.list
      } else if (state.viewkey === 'undone') {
        return state.list.filter(x => x.done === false)
      } else if (state.viewkey === 'done') {
        return state.list.filter(x => x.done === true)
      } else {
        return state.list
      }
    }
  }
})
